import XLSX, { WorkSheet } from 'xlsx';

export const exportExcel = (id: string, sheetName: string, excelName: string) => {
	let worksheet: WorkSheet = XLSX.utils.table_to_sheet(document.getElementById(id));
	Object.keys(worksheet).forEach(cellAddress => {
        const cell = worksheet[cellAddress];
        const col = cellAddress.replace(/[0-9]/g, ''); // 提取列字母（如 A、B、C）
		const textColumns = ['A','B', 'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','S','T','U','V','W','X','Y','Z']; // 需要设置为文本的列（A=id列, C=phone列）
        if (textColumns.includes(col)) {
			//数据转成字符串
			if(cell.t === 'n' && !cell.z){
				cell.t = 's'; // 类型设为字符串
          		cell.z = '@';  // Excel 格式代码 "@" 表示文本格式
			}
        }
	});
	console.log(worksheet);
	let workbook = XLSX.utils.book_new();
	XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
	XLSX.writeFile(workbook, excelName);
};

export const exportExcelFromJson = (data: Array<any>,header:any, sheetName: string, excelName: string) => {
	let worksheet: WorkSheet = XLSX.utils.json_to_sheet(data,{header:header});
	console.log(data);
	let workbook = XLSX.utils.book_new();
	XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
	XLSX.writeFile(workbook, excelName);
};
